package com.winchain.chainbill.esign.service.impl;

import com.shell.bee.base.exception.UnCheckMsgException;
import com.shell.bee.base.utils.StringUtil;
import com.shell.bee.base.utils.SystemUtil;
import com.shell.bee.cfca.paperless.request.CfcaBatchSignRequest;
import com.shell.bee.cfca.paperless.request.CfcaBatchSignRequest.BatchSignParam;
import com.shell.bee.cfca.paperless.response.BaseResponse;
import com.shell.bee.cfca.paperless.service.CfcaSignTxService;
import com.shell.bee.contract.ContService;
import com.shell.bee.contract.po.ContBas;
import com.shell.bee.contract.po.ContProt;
import com.shell.bee.contract.po.ContTmpl;
import com.shell.bee.esign.po.EsCust;
import com.shell.bee.esign.service.EsCustService;
import com.shell.bee.esign.service.EsignSealService;
import com.shell.bee.esign.service.EsignSignService;
import com.shell.bee.esign.vo.MultiSignVo;
import com.shell.bee.report.utils.FilePathHelper;
import com.shell.bee.report.utils.PdfUtils;
import com.shell.feign.PubUserFeign;
import com.shell.framework.utils.CommonDataUtil;
import com.shell.governor.user.po.PubUser;
import com.timevale.esign.sdk.tech.bean.result.AddSealResult;
import com.timevale.esign.sdk.tech.bean.result.CodeMultiSignResult;
import com.timevale.esign.sdk.tech.bean.seal.OrganizeTemplateType;
import com.timevale.esign.sdk.tech.bean.seal.PersonTemplateType;
import com.timevale.esign.sdk.tech.bean.seal.SealColor;
import com.winchain.chainbill.ChainBillUtil;
import com.winchain.chainbill.basic.cus.po.CusRec;
import com.winchain.chainbill.basic.cus.service.CusRecService;
import com.winchain.chainbill.esign.service.BatchSignService;
import com.winchain.chainbill.esign.vo.BatchSignVo;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BatchSignServiceImpl implements BatchSignService {
	@Autowired
	private CusRecService cusRecService;
	@Autowired
	private EsCustService esCustService;
	@Autowired
	private EsignSealService esignSealService;
	@Autowired
	private ContService contService;
	@Autowired
	private EsignSignService esignSignService;
	@Autowired
	private PubUserFeign pubUserFeign;
	@Autowired
	private CfcaSignTxService cfcaSignTxService;

	public void batchSign(BatchSignVo batchSignVo) {
		if (ChainBillUtil.onEsign()) {
			signByEsign(batchSignVo);
		} else if (ChainBillUtil.onCfca()) {
			signByCfcaPaperless(batchSignVo);
		}
	}

	private void signByCfcaPaperless(BatchSignVo batchSignVo) {
		String entId = CommonDataUtil.getCurEntId();
		if (StringUtil.notEmpty(batchSignVo.getCusId())) {
			entId = batchSignVo.getCusId();
		}
		PubUser user = this.pubUserFeign.selectByKey(CommonDataUtil.getUserId());
		CusRec curCus = (CusRec) this.cusRecService.selectByKey(entId);
		List<ContBas> conts = new ArrayList();
		CfcaBatchSignRequest request = new CfcaBatchSignRequest();
		CfcaBatchSignRequest.BatchSignParam batchSignParam = null;
		List<String> signBillIds = batchSignVo.getSignBillIds();
		for (Iterator localIterator = signBillIds.iterator(); localIterator.hasNext();) {
			String signBillId = (String) localIterator.next();
			ContBas cont = this.contService.getLatestCont(entId, signBillId, batchSignVo.getBizType(), null);
			if (cont == null) {
				throw new UnCheckMsgException("����������");
			}
			conts.add(cont);
			List<ContProt> prots = null;
			prots = this.contService.selectProts(cont.getContId());
			if ((prots != null) && (prots.size() > 0)) {
				ContProt contProt = (ContProt) prots.get(0);
				ContTmpl contTmpl = this.contService.selectContTmplByKey(contProt.getTmplId());
				batchSignParam = new CfcaBatchSignRequest.BatchSignParam();
				if (entId.equals(cont.getSponsor())) {
					batchSignParam.setSignPage(Integer.parseInt(contTmpl.getSponsorPage()));
					batchSignParam.setKeyIndex(contTmpl.getSponsorKeyIndex());
				} else if (entId.equals(cont.getAcceptor())) {
					batchSignParam.setSignPage(Integer.parseInt(contTmpl.getAcceptorPage()));
					batchSignParam.setKeyIndex(contTmpl.getAcceptorKeyIndex());
				} else {
					batchSignParam.setSignPage(Integer.parseInt(contTmpl.getSponsorPage()));
					batchSignParam.setKeyIndex(contTmpl.getWitnessKeyIndex());
				}
				batchSignParam.setKey(curCus.getCusName());
				batchSignParam.setContId(cont.getContId());
				batchSignParam.setSrcPdfPath(contProt.getProtLoc());
				batchSignParam.setDestPdfPath(
						FilePathHelper.replaceFileName(contProt.getProtLoc(), SystemUtil.getUUID(), "pdf"));
				batchSignParam.setProtId(contProt.getProtId());
				request.addBatchSignParam(batchSignParam);
			}
		}
		String signBillId;
		request.setUserId(user.getUserId());
		request.setUserName(user.getUserName());
		request.setIdNo(user.getCertNo());
		request.setPhoneNo(user.getPhoneNo());
		request.setPhoneCode(batchSignVo.getPhoneCode());
		request.setCusId(entId);
		request.setCusName(curCus.getCusName());
		request.setLocation(batchSignVo.getLocation());
		request.setReason(batchSignVo.getReason());
		request.setSealCode(batchSignVo.getSealCode());

		BaseResponse response = this.cfcaSignTxService.batchSign(request);
		if (!response.isSuccess()) {
			throw new UnCheckMsgException("������������������cfca��" + response.getMessage());
		}
		updateConts(conts, entId);
		for (CfcaBatchSignRequest.BatchSignParam signParam : request.getBatchSignParams()) {
			updateProtLoc(signParam.getProtId(), signParam.getSrcPdfPath(), signParam.getDestPdfPath());
		}
	}

	public void updateConts(List<ContBas> conts, String entId) {
		for (ContBas cont : conts) {
			boolean finished = false;
			if (!entId.equals(cont.getSponsor())) {
				if ("18".equals(cont.getBizType())) {
					if (entId.equals(cont.getWitness())) {
						finished = true;
					}
				} else if (entId.equals(cont.getAcceptor())) {
					finished = true;
				}
			}
			if (finished) {
				cont.setContProgress("1");
			}
			this.contService.sign(cont, entId);
		}
	}

	private void signByEsign(BatchSignVo batchSignVo) {
		String entId = CommonDataUtil.getCurEntId();
		PubUser user = this.pubUserFeign.selectByKey(CommonDataUtil.getUserId());
		CusRec curCus = (CusRec) this.cusRecService.selectByKey(entId);

		AddSealResult seal = null;
		EsCust esCust;
		if ("PERSONAL".equals(curCus.getCusType())) {
			esCust = (EsCust) this.esCustService.selectByKey(CommonDataUtil.getUserId());
			seal = this.esignSealService.getPersonSeal(esCust.getAcctId(), PersonTemplateType.RECTANGLE, SealColor.RED);
		} else {
			esCust = (EsCust) this.esCustService.selectByKey(entId);
			seal = this.esignSealService.getOrganizeSeal(esCust.getAcctId(), OrganizeTemplateType.STAR, SealColor.RED,
					"", "");
		}
		List<ContBas> conts = new ArrayList();
		List<MultiSignVo> multiSignVos = new ArrayList();
		MultiSignVo multiSignVo = null;
		for (Iterator localIterator = batchSignVo.getSignBillIds().iterator(); localIterator.hasNext();) {
			String signBillId = (String) localIterator.next();
			multiSignVo = new MultiSignVo();
			ContBas cont = this.contService.getLatestCont(entId, signBillId, batchSignVo.getBizType(), null);
			if (cont != null) {
				List<ContProt> prots = null;
				prots = this.contService.selectProts(cont.getContId());
				if ((prots != null) && (prots.size() > 0)) {
					ContProt contProt = (ContProt) prots.get(0);
					multiSignVo.setContId(cont.getContId());
					multiSignVo.setProtId(contProt.getProtId());
					multiSignVo.setSrcPdfPath(contProt.getProtLoc());
					multiSignVo.setDestPdfPath(
							FilePathHelper.replaceFileName(contProt.getProtLoc(), SystemUtil.getUUID(), "pdf"));

					Map<String, String> positon = PdfUtils.getKeyFirstPosition(contProt.getProtLoc(),
							esCust.getCustNm());
					if (positon.size() == 0) {
						throw new UnCheckMsgException("������������");
					}
					multiSignVo.setSignPage((String) positon.get("page"));
					multiSignVo.setX((String) positon.get("X"));
					multiSignVo.setY((String) positon.get("Y"));
				} else {
					throw new UnCheckMsgException("����������");
				}
				conts.add(cont);
			} else {
				throw new UnCheckMsgException("����������");
			}
			multiSignVos.add(multiSignVo);
		}
		String signBillId;
		CodeMultiSignResult codeMultiSignResult = this.esignSignService.sign(esCust.getAcctId(), seal.getSealData(),
				multiSignVos, user.getPhoneNo(), batchSignVo.getPhoneCode(), esCust.getCustId());
		if ((codeMultiSignResult.getErrCode() != 0)
				|| (batchSignVo.getSignBillIds().size() != codeMultiSignResult.getSuccessList().size())) {
			throw new UnCheckMsgException("������������������e������" + codeMultiSignResult.getMsg());
		}
		updateConts(conts, entId);
		for (MultiSignVo vo : multiSignVos) {
			if (StringUtil.notEmpty(vo.getDestPdfPath())) {
				updateProtLoc(vo.getProtId(), vo.getSrcPdfPath(), vo.getDestPdfPath());
			}
		}
	}

	public void updateProtLoc(String protId, String srcPdfPath, String pdfPath) {
		this.contService.updateProtLoc(protId, pdfPath);
		File tmp = new File(srcPdfPath);
		if (tmp.exists()) {
			tmp.delete();
		}
	}
}
